#!/bin/bash

# 注：需与.jar文件处于同一级目录，且该目录内只有一个.jar文件，如无法满足，则修改如下的：appUrl
# 参数1：start | stop | status | restart
# 参数2：jar文件路径，如 ./mo/mo.jar
# 参数3和参数4：堆大小，如 128m 256m

appUrl='*.jar'
# logUrl='log.file'
if [ $2 ]; then
    appUrl=$2
    # %/* 表示从右边开始，删除第一个 / 号及右边的字符
    # logUrl=${appUrl%/*}'/log.file'
fi
# 堆大小
xms='-Xms128m'
xmx='-Xmx256m'
if [ $3 ]; then
    xms='-Xms'$3
fi
if [ $4 ]; then
    xmx='-Xmx'$4
fi

appName=`ls $appUrl`
appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`
appParam='-Dfile.encoding=UTF-8'

if [ ! $1 ]; then
  echo "请输入操作: 'start | stop | restart | status'"
  exit
fi

# 启动函数
startApp(){
  if [ ! $appPid ]; then
      echo "$appName status: 加载java环境....."
      source /etc/profile

      echo -n "$appName status: 正在启动....."
      # /dev/null属于字符特殊文件，它属于空设备，是一个特殊的设备文件，它会丢弃一切写入其中的数据
      nohup java $xms $xmx $appParam -jar $appUrl > /dev/null 2>&1 &
      echo -n " "

      count=0;
      while ((count <= 20)) ; do
          echo -n "."
          if [ ! $appPid ]; then
              sleep 2
              appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`
              ((count += 1))
          else
              break
          fi
      done

      echo ""
      if [ ! $appPid ]; then
          echo "$appName status: 启动失败!"
      else
          echo "$appName status: 启动成功，PID = $appPid"
      fi
  else
      echo "$appName status: 运行中，请勿重复启动!"
  fi
}

# 停止函数
stopApp(){
  if [ $appPid ]; then
      echo -n "$appName status: 正在停止....."
      kill -2 $appPid
      echo -n " "

      count=0;
      while ((count <= 20)) ; do
          sleep 3
          echo -n "."
          appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`

          if [ $appPid ]; then
              ((count += 1))

              if [ $count == 21 ]; then
                  kill -9 $appPid
              fi
          else
              break
          fi
      done

      echo ""
      echo "$appName status: 停止成功!"
  else
      echo "$appName status: 未运行, 停止失败!"
  fi
}

if [ $1 == "status" ]; then
  echo "----------服务名称: $appName server, pid = $appPid ----------"
fi

if [ $1 == "start" ]; then
  startApp
fi

if [ $1 == "stop" ]; then
  stopApp
fi

if [ $1 == "restart" ]; then
  sh currency_deploy.sh stop $2 $3 $4
  sleep 3
  sh currency_deploy.sh start $2 $3 $4
fi